home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C25 / ShapeFactory1.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.8 KB  |  75 lines

  1. //: C25:ShapeFactory1.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. #include "../purge.h"
  7. #include <iostream>
  8. #include <string>
  9. #include <exception>
  10. #include <vector>
  11. using namespace std;
  12.  
  13. class Shape {
  14. public:
  15.   virtual void draw() = 0;
  16.   virtual void erase() = 0;
  17.   virtual ~Shape() {}
  18.   class BadShapeCreation : public exception {
  19.     string reason;
  20.   public:
  21.     BadShapeCreation(string type) {
  22.       reason = "Cannot create type " + type;
  23.     }
  24.     const char *what() const { 
  25.       return reason.c_str(); 
  26.     }
  27.   };
  28.   static Shape* factory(string type) 
  29.     throw(BadShapeCreation);
  30. };
  31.  
  32. class Circle : public Shape {
  33.   Circle() {} // Private constructor
  34.   friend class Shape;
  35. public:
  36.   void draw() { cout << "Circle::draw\n"; }
  37.   void erase() { cout << "Circle::erase\n"; }
  38.   ~Circle() { cout << "Circle::~Circle\n"; }
  39. };
  40.  
  41. class Square : public Shape {
  42.   Square() {}
  43.   friend class Shape;
  44. public:
  45.   void draw() { cout << "Square::draw\n"; }
  46.   void erase() { cout << "Square::erase\n"; }
  47.   ~Square() { cout << "Square::~Square\n"; }
  48. };
  49.  
  50. Shape* Shape::factory(string type) 
  51.   throw(Shape::BadShapeCreation) {
  52.   if(type == "Circle") return new Circle();
  53.   if(type == "Square") return new Square();
  54.   throw BadShapeCreation(type);
  55. }
  56.  
  57. char* shlist[] = { "Circle", "Square", "Square",
  58.   "Circle", "Circle", "Circle", "Square", "" };
  59.  
  60. int main() {
  61.   vector<Shape*> shapes;
  62.   try {
  63.     for(char** cp = shlist; **cp; cp++)
  64.       shapes.push_back(Shape::factory(*cp));
  65.   } catch(Shape::BadShapeCreation e) {
  66.     cout << e.what() << endl;
  67.     return 1;
  68.   }
  69.   for(int i = 0; i < shapes.size(); i++) {
  70.     shapes[i]->draw();
  71.     shapes[i]->erase();
  72.   }
  73.   purge(shapes);
  74. } ///:~
  75.